import allure
from tests.dayu_business_background.dayu_coupon.py_msql import *
from tests.dayu_business_background.dayu_coupon.coupon_config import *

# 文件路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))


class Coupon(object):

    def __init__(self):
        self.cursor = DButil

    @allure.step("查询sql语句")
    def sql_inquire(self, env, value, chart_name="coupon_base_info", name="name"):
        sql = "select * from {} where {}='{}'".format(chart_name, name, value)
        data = self.cursor.get_sql_info(env, sql=sql)
        for i in data:
            return i

    @allure.step("获取参数化内容")
    def all_build_data(self, path):
        test_data = []
        with open(
                BASE_DIR + path, "r",
                encoding="utf-8") as f:
            json_data = json.load(f)
        for i in json_data:
            test_data.append((i.get("name"), i.get("effectivePeriodType"), i.get("relativeEffectivePeriod"),
                              i.get("openDayType"), i.get("openDateDays"), i.get("openWeekDays"), i.get("openTimes"),
                              i.get("openTimeType"), i.get("circulation"), i.get("codeSourceType"), i.get("externalId"),
                              i.get("isIsolateStock"), i.get("stockChannelAllocation"), i.get("isRestrictive"),
                              i.get("grantRestriction"), i.get("fitBranchScopeType"), i.get("fitPublishChannels"),
                              i.get("fitTradeScenes"), i.get("preferentialInfo"), i.get("relationExternal"),
                              i.get("type"), i.get("verifyDayType"), i.get("verifyTimeType"), i.get("verifyThreshold")))
        Logger("coupon", "coupon_data").logger.info("测试数据：{}".format(test_data))
        return test_data

    @allure.step("获取token")
    def get_token(self, env, user, pwd, headers_merchant):
        # 中台登录域名
        base_url = getconf(env, "zhongtai_url")
        url = base_url + "buorg/v1/session/login"
        data = {
            "account": user,
            "password": pwd
        }
        return requests.post(url, json=data, headers=headers_merchant)

    @allure.step("卡券分类列表")
    def coupon_categories(self, env, headers_merchant):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/dict/couponType/list'
        return requests.get(url, headers=headers_merchant)

    @allure.step("创建卡券")
    def create_coupon(self, env, headers_merchant, name, effectiveperiodtype, relativeeffectiveperiod, opendaytype,
                      opendatedays, openweekdays, opentimes, opentimetype, circulation, codesourcetype, externalid,
                      isisolatestock,
                      stockchannelallocation, isrestrictive, grantrestriction, fitbranchscopetype, fitpublishchannels,
                      fittradescenes, preferentialInfo, relationexternal, type, verifydaytype, verifytimetype,
                      verifythreshold):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + "platform-coupon-server/v1/coupon/create"
        data = {
            "absoluteEffectivePeriod": {
                "effectiveTime": start,
                "expiryTime": end
            },
            "externalInfo": None,
            "gregariousLevel": "STANDALONE",
            "imgUrl": "",
            "openEndDate": end_time,
            "openStartDate": start_time,
            "remark": "",
            "sketch": "",
            "name": name,
            "effectivePeriodType": effectiveperiodtype,
            "relativeEffectivePeriod": relativeeffectiveperiod,
            "openDayType": opendaytype,
            "openDateDays": opendatedays,
            "openWeekDays": openweekdays,
            "openTimeType": opentimetype,
            "openTimes": opentimes,
            "circulation": circulation,
            "codeSourceType": codesourcetype,
            "externalId": externalid,
            "isIsolateStock": isisolatestock,
            "stockChannelAllocation": stockchannelallocation,
            "isRestrictive": isrestrictive,
            "grantRestriction": grantrestriction,
            "fitBranchScopeType": fitbranchscopetype,
            "fitPublishChannels": fitpublishchannels,
            "fitTradeScenes": fittradescenes,
            "preferentialInfo": preferentialInfo,
            "relationExternal": relationexternal,
            "type": type,
            "validEndDate": end_time,
            "validStartDate": start_time,
            "verifyDayType": verifydaytype,
            "verifyThreshold": verifythreshold,
            "verifyTimeType": verifytimetype
        }
        print(headers_merchant)
        return requests.post(url=url, json=data, headers=headers_merchant)

    @allure.step("修改卡券")
    def update_coupon(self, env, couponid, headers_merchant, openstartdata=start_time):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + "platform-coupon-server/v1/coupon/update"
        data = {
            "id": couponid,
            "absoluteEffectivePeriod": {
                "effectiveTime": start,
                "expiryTime": end
            },
            "circulation": 999,
            "effectivePeriodType": "ABSOLUTE_TIME",
            "externalInfo": None,
            "fitBranchScopeType": "ALL_POINT",
            "fitPublishChannels": [
                "PRECISE_MARKETING",
                "THIRD_PARTY",
                "INTERACTIVE_MARKETING",
                "ONLINE_MARKETING",
                "VIRTUAL_GOODS",
                "WECHAT_MINI_PROGRAM",
                "MODULE_MEMBER_BACKEND",
                "H5"
            ],
            "fitTradeScenes": [
                "OFFLINE",
                "INTERACTIVE_MARKETING",
                "E_COMMERCE"
            ],
            "gregariousLevel": "STANDALONE",
            "imgUrl": "https://rongyi.b0.rongyi.com/commodity/text/202011191532423126.png",
            "isIsolateStock": "false",
            "isRestrictive": "false",
            "name": "自动化专用卡券_时长券",
            "openDayType": "ALWAYS",
            "openEndDate": end_time,
            "openStartDate": openstartdata,
            "openTimeType": "ALWAYS",
            "preferentialInfo": {
                "deductHours": 1,
                "limitDiscountCashAmount": "false",
                "maxDiscountCashAmount": 0
            },
            "relationExternal": "false",
            "remark": "",
            "sketch": "",
            "syncWechat": "false",
            "type": "DURATION",
            "validEndDate": end_time,
            "validStartDate": start_time,
            "verifyDayType": "ALWAYS",
            "verifyTimeType": "ALWAYS"
        }
        return requests.post(url=url, json=data, headers=headers_merchant)

    @allure.step("卡券批量发布")
    def couponpublishbatched(self, env, id_list, headers_merchant):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/coupon/publishBatched'
        data = {"ids": id_list}
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("卡券基本信息详情")
    def coupon_details(self, env, couponid, headers_merchant):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/coupon/detail/'
        data = {"id": couponid}
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("查看卡券列表")
    def coupon_list(self, env, name, types, status, queryscope, headers_merchant, current=1, size=20):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + "platform-coupon-server/v1/coupon/pageList"
        data = {
            "name": name,
            "types": types,
            "status": status,
            "queryScope": queryscope,
            "current": current,
            "size": size
        }
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("发布卡券")
    def publish_coupon(self, env, headers_merchant, couponid):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + "platform-coupon-server/v1/coupon/publish"
        data = {"id": couponid}
        return requests.post(url=url, json=data, headers=headers_merchant)

    @allure.step("审核卡券")
    def checkpass(self, env, couponid, headers_merchant):
        """审核卡券"""
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + "platform-coupon-server/v1/coupon/audit/permit"
        data = {"id": couponid}
        return requests.post(url=url, json=data, headers=headers_merchant)

    @allure.step("卡券状态变更")
    def change_coupon_status(self, env, status, couponid, headers_merchant):
        """status:freeze(冻结)/unfreeze(解冻)"""
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/coupon/{}'.format(status)
        data = {"id": couponid}
        return requests.post(url, json=data, headers=headers_merchant)

    @allure.step("发券记录查询")
    def pagelist_coupon(self, env, couponcode, couponname, coupontype, grantstarttime,
                        grantendtime, ownerbranchname, verifystarttime, verifyendtime, headers_merchant, current=1,
                        size=10,
                        ):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/grantRecord/pageList'
        data = {
            "couponCode": couponcode,
            "couponName": couponname,
            "couponTypes": coupontype,
            "current": current,
            "grantEndTime": grantendtime,
            "grantStartTime": grantstarttime,
            "ownerBranchName": ownerbranchname,
            "size": size,
            "verifyEndTime": verifyendtime,
            "verifyStartTime": verifystarttime
        }
        return requests.post(url, json=data, headers=headers_merchant)

    @allure.step("券码核销")
    def verify_couponcode(self, env, couponcode, headers_merchant):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/verify'
        data = {"couponCode": couponcode}
        return requests.post(url, json=data, headers=headers_merchant)

    @allure.step("获取会员相关信息")
    def member_details(self, env, headers_merchant, page_num=1, num=5):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-member-server/v1/member/page'
        data = {"current": page_num,
                "size": num}
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("指定会员发放卡券")
    def grantmembercouponcode(self, env, couponid, membercode, headers_merchant, num=1):
        """
        couponid：卡券id，membercode：会员cardcode
        """
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/memberCouponCode/grant'
        data = {"couponId": couponid,
                "memberCardCode": membercode,
                "quantity": num}
        return requests.post(url, json=data, headers=headers_merchant)

    @allure.step("查询会员券码数量")
    def membercouponcode(self, env, memberid, startgroup, headers_merchant):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/memberCouponCode/count'
        data = {"memberId": memberid,
                "statusGroup": startgroup}
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("会员券码列表查询")
    def pageList(self, env, memberid, startgroup, headers_merchant, current=1, size=20):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/memberCouponCode/pageList'
        data = {"current": current,
                "memberId": memberid,
                "size": size,
                "statusGroup": startgroup}
        return requests.post(url, json=data, headers=headers_merchant)

    @allure.step("卡券基本信息删除")
    def delete_coupon(self, env, couponid, headers_merchant):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/coupon/delete'
        data = {"id": couponid}
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("核销记录概要")
    def summary(self, env, headers_merchant):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + "platform-coupon-server/v1/verifyRecord/overview"
        return requests.get(url, headers=headers_merchant)

    @allure.step("核销记录分页查询")
    def query_verify(self, env, couponcode, coupontypes, couponname, serialno, verifystarttime, verifyendtime,
                     headers_merchant,
                     current=1, size=10):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/verifyRecord/pageList'
        data = {
            "couponCode": couponcode,
            "couponTypes": coupontypes,
            "couponName": couponname,
            "serialNo": serialno,
            "current": current,
            "size": size,
            "verifyStartTime": verifystarttime,
            "verifyEndTime": verifyendtime
        }
        return requests.post(url, json=data, headers=headers_merchant)

    @allure.step("审核日志列表")
    def couponauditlogpagelist(self, env, couponname, coupontypes, ownerbranchname, headers_merchant, current=1,
                               size=10):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/couponAuditLog/pageList'
        data = {
            "couponName": couponname,
            "couponTypes": coupontypes,
            "current": current,
            "ownerBranchName": ownerbranchname,
            "size": size
        }
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("卡券审核详情")
    def couponauditlogdetail(self, env, check_couponid, headers_merchant):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/couponAuditLog/detail'
        data = {"id": check_couponid}
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("卡券详情快照")
    def couponauditlogcouponsnapshot(self, env, check_couponid, headers_merchant):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/couponAuditLog/couponSnapshot'
        data = {"id": check_couponid}
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("创建卡券组合")
    def couponpkgcreate(self, env, coupons, name, publishchannel, vaildendtime, validstarttime, headers_merchant,
                        imgurl=None):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/coupon/pkg/create'
        data = {"coupons": coupons,
                "imgUrl": imgurl,
                "name": name,
                "publishChannel": publishchannel,
                "validEndTime": vaildendtime,
                "validStartTime": validstarttime}
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("卡券组合详情")
    def couponpkgdetail(self, env, group_couponid, headers_merchant):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/coupon/pkg/detail'
        # 组合卡券ID
        data = {"id": group_couponid}
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("编辑组合卡券")
    def update_pkg_coupon(self, env, pkg_coupon_id, coupons, name, publishchannel, vaildendtime, validstarttime,
                          headers_merchant,
                          imgurl=None):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/coupon/pkg/update'
        data = {
            "id": pkg_coupon_id,
            "coupons": coupons,
            "imgUrl": imgurl,
            "name": name,
            "publishChannel": publishchannel,
            "validEndTime": vaildendtime,
            "validStartTime": validstarttime}
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("卡券组合状态改变")
    def change_couponpkg(self, env, status, group_couponid, headers_merchant):
        """freeze:冻结/unfreeze:恢复"""
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/coupon/pkg/{}'.format(status)
        # 组合卡券ID
        data = {"id": group_couponid}
        return requests.post(url, headers=headers_merchant, json=data)

    @allure.step("卡券组合列表")
    def couponpkgpageList(self, env, name, statues, headers_merchant, current=1, size=10):
        # 中台登录域名
        base_domain = getconf(env, "zhongtai_url")
        url = base_domain + 'platform-coupon-server/v1/coupon/pkg/pageList'
        data = {"name": name,
                "statuses": statues,
                "current": current,
                "size": size,
                }
        return requests.post(url, headers=headers_merchant, json=data)
